<template>
  <view class="authComponent">
    <!-- 密码认证 -->
    <u-keyboard
      ref="uKeyboard"
      v-model="password.show"
      :dot-enabled="false"
      :mask="true"
      :mask-close-able="false"
      :safe-area-inset-bottom="true"
      :tooltip="false"
      default=""
      mode="number"
      @backspace="onBackspace"
      @change="onChange"
    >
      <view>
        <view class="u-text-center u-padding-20 keyboard-title">
          <text class="title">{{ title }}</text>
          <view class="subTitle">{{ subTitle }}</view>
          <view class="u-padding-10 close" data-flag="false" @tap="close()">
            <u-icon color="#333333" name="close" size="28"></u-icon>
          </view>
        </view>
        <view class="u-flex u-row-center">
          <u-message-input
            v-model="password.inputPassword"
            :disabled-keyboard="true"
            :dot-fill="true"
            :maxlength="6"
            mode="box"
            @finish="finish"
          ></u-message-input>
        </view>
        <view class="u-text-center u-padding-top-10 u-padding-bottom-20 tips"></view>
      </view>
    </u-keyboard>
    <!-- 指纹认证 -->
    <u-modal
      v-model="finger.show"
      :async-close="true"
      :content="finger.content"
      :show-confirm-button="false"
      :title="finger.title"
      show-cancel-button
      @cancel="close()"
    >
      <view class="modal-content">
        <view class="modal-password" @click="userPassword">{{$t('使用密码解锁')}}</view>
        <view :animation="finger.animationData">
          <u-icon color="#2979ff" name="fingerprint" size="100"></u-icon>
        </view>
        <view class="center-text">{{ finger.text }}</view>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapGetters(['userInfo', 'api', 'app'])
  },
  props: {
    title: {
      type: String,
      default: () => {
        return ''
      }
    },
    subTitle: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      password: {
        show: false,
        inputPassword: ''
      },
      finger: {
        animationData: {},
        show: false,
        title: '',
        content: '',
        text: this.$t('请用指纹解锁')
      },
      isUserPassword: false //是否从指纹模式切换至密码模式
    }
  },
  mounted() {
    this.animation = uni.createAnimation({
      duration: 100,
      timingFunction: 'ease'
    })
  },
  onShow() {},
  methods: {
    // 指纹模式切换至密码模式
    userPassword() {
      this.isUserPassword = true
      // #ifdef APP-PLUS
      plus.fingerprint.cancel()
      // #endif
      this.initFinger()
      //使用密码模式
      this.password.inputPassword = ''
      this.password.show = true
    },
    initFinger() {
      this.finger = {
        animationData: {},
        show: false,
        title: '',
        content: '',
        text: this.$t('请用指纹解锁')
      }
    },
    animationFn() {
      this.animation.scale(0.5, 0.5).opacity(0.5).step()
      this.finger.animationData = this.animation.export()
      setTimeout(() => {
        this.animation.scale(1, 1).opacity(1).step()
        this.finger.animationData = this.animation.export()
      }, 100)
    },
    fingerprint() {
      // #ifdef APP-PLUS
      plus.fingerprint.authenticate(() => {
          this.animationFn()
          //指纹识别成功
          this.finger.text = this.$t('指纹识别成功')
          setTimeout(() => {
            this.finger.show = false
            this.$emit('submit', '指纹验证成功')
            this.initFinger()
          }, 500)
        }, (e) => {
          this.animationFn()
          switch (e.code) {
            case e.AUTHENTICATE_MISMATCH:
              this.finger.text = this.$t('指纹匹配失败，请重新输入')
              break
            case e.AUTHENTICATE_OVERLIMIT:
              this.finger.text = this.$t('指纹识别失败次数超出限制,稍后再试')
              break
            case e.CANCEL:
              this.finger.text = this.$t('已取消识别')
              break
            default:
              this.finger.text = this.$t('指纹识别失败，请重试')
              break
          }
        }
      )
      // Android平台手动弹出等待提示框
      if ('Android' === plus.os.name) {
        this.finger.show = true
      }
      // #endif
      // #ifdef MP-WEIXIN
      wx.startSoterAuthentication({
        requestAuthModes: ['fingerPrint'],
        challenge: '123456',
        authContent: this.$t('请用指纹解锁'),
        success(res) {
          uni.showToast({
            title: this.$t('识别成功'),
            mask: false,
            duration: 1500
          })
        }
      })
      // #endif
    },
    onChange(val) {
      if (this.password.inputPassword.length < 6) {
        this.password.inputPassword += val
      }
      if (this.password.inputPassword.length >= 6) {
        this.submit()
      }
    },
    onBackspace() {
      if (this.password.inputPassword.length > 0) {
        this.password.inputPassword = this.password.inputPassword.substring(
          0,
          this.password.inputPassword.length - 1
        )
      }
    },
    submit() {
      this.$emit('submit', this.password.inputPassword)
    },
    close() {
      // #ifdef APP-PLUS
      plus.fingerprint.cancel()
      // #endif
      this.$emit('close', this.password.inputPassword)
    },
    showPop(flag = true, text) {
      if (flag) {
        if (this.app.noPasswordPrint === true && text !== '无密码认证开启') {
          this.$emit('submit', '无密码认证')
          return
        }
        if (this.app.noPasswordPrint && text === '无密码认证开启') {
          this.password.inputPassword = ''
          this.password.show = flag
          return
        }
        //检测是否设置过认证密码
        if (!this.userInfo.hasCertKey) {
          uni.showModal({
            title: this.$t('提示'),
            content: this.$t('检测到您未设置安全认证密码，请先设置后再操作'),
            cancelText: this.$t('取消'),
            confirmText: this.$t('确定'),
            success: (res) => {
              //console.log(res.confirm);
              if (res.confirm) {
                uni.navigateTo({
                  url: `/pages/template/safetyCertification/setPassword/setPassword?title=${this.$t('设置认证密码')}&subTitle=${this.$t('请输入认证密码，以验证身份')}`
                })
              }
              if (res.cancel) {
                this.close()
              }
            }
          })
          return
        }
        if (this.title === '指纹开关' || this.title === '修改认证密码') {
          this.password.inputPassword = ''
          this.password.show = flag
          return
        }
        //当前开启指纹认证并且手机支持指纹认证
        if (this.app.fingerPrint && this.app.supportMode.includes('fingerPrint')) {
          // this.initFinger()
          this.fingerprint()
        } else {
          //console.log('未开启指纹认证');
          this.password.inputPassword = ''
          this.password.show = flag
        }
      } else {
        this.password.show = flag
      }
    },
    initPassword() {
      this.password.inputPassword = ''
    },
    finish() {}
  }
}
</script>

<style lang="scss" scoped>
.authComponent {
  // 密码
  .keyboard-title {
    font-size: 40rpx;
    position: relative;

    .title {
      font-weight: bold;
      line-height: 80rpx;
    }

    .subTitle {
      font-size: 30rpx;
    }

    .close {
      position: absolute;
      top: 20rpx;
      right: 20rpx;
      line-height: 28rpx;
      font-size: 28rpx;
    }
  }

  // 指纹
  .modal-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
    position: relative;

    .center-text {
      margin-top: 10px;
      color: #888;
    }

    .modal-password {
      position: absolute;
      right: 10px;
      top: -10px;
      font-size: 26rpx;
      font-weight: bold;
      color: #888;
    }
  }
}
</style>
